package io.github.jsp.tranvolume.mapper;

import io.github.jsp.tranvolume.entity.TranFailCode;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 失败响应码统计Mapper
 */
@Mapper
public interface TranFailCodeMapper {

    @Select("SELECT * FROM tran_fail_code WHERE minute_time BETWEEN #{startTime} AND #{endTime} ORDER BY minute_time DESC")
    List<TranFailCode> findByTimeRange(@Param("startTime") LocalDateTime startTime, 
                                      @Param("endTime") LocalDateTime endTime);

    @Select("SELECT * FROM tran_fail_code WHERE minute_time BETWEEN #{startTime} AND #{endTime} " +
            "AND center = #{center} ORDER BY minute_time DESC")
    List<TranFailCode> findByTimeRangeAndCenter(@Param("startTime") LocalDateTime startTime, 
                                               @Param("endTime") LocalDateTime endTime,
                                               @Param("center") String center);

    @Select("SELECT ret_code, SUM(fail_count) as fail_count " +
            "FROM tran_fail_code WHERE minute_time BETWEEN #{startTime} AND #{endTime} " +
            "GROUP BY ret_code ORDER BY fail_count DESC LIMIT #{limit}")
    List<Map<String, Object>> getTopFailCodes(@Param("startTime") LocalDateTime startTime, 
                                             @Param("endTime") LocalDateTime endTime,
                                             @Param("limit") Integer limit);

    @Select("SELECT center, ret_code, SUM(fail_count) as fail_count " +
            "FROM tran_fail_code WHERE minute_time BETWEEN #{startTime} AND #{endTime} AND center = #{center} " +
            "GROUP BY center, ret_code ORDER BY fail_count DESC LIMIT #{limit}")
    List<Map<String, Object>> getTopFailCodesByCenter(@Param("startTime") LocalDateTime startTime, 
                                                      @Param("endTime") LocalDateTime endTime,
                                                      @Param("center") String center,
                                                      @Param("limit") Integer limit);

    @Insert("INSERT INTO tran_fail_code (minute_time, center, service_plat, ret_code, fail_count) " +
            "VALUES (#{minuteTime}, #{center}, #{servicePlat}, #{retCode}, #{failCount}) " +
            "ON CONFLICT (minute_time, center, service_plat, ret_code) DO UPDATE SET " +
            "fail_count = fail_count + #{failCount}")
    int insertOrUpdate(TranFailCode record);

    @Select("SELECT ret_code, SUM(fail_count) as fail_count " +
            "FROM tran_fail_code WHERE minute_time >= NOW() - INTERVAL '30 minutes' " +
            "GROUP BY ret_code ORDER BY fail_count DESC LIMIT 10")
    List<Map<String, Object>> getRecentTopFailCodes();
}